<template>
	<dt-main-body v-model="labelPosition">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>文章管理</el-breadcrumb-item>
				<el-breadcrumb-item>编辑内容</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="content-box">
			<el-form ref="editForm" :model="model" :rules="rules" :label-position="labelPosition" label-width="120px">
				<el-tabs v-model="activeName" type="card">
					<el-tab-pane label="基本信息" name="info">
						<div class="tab-content">
							<el-form-item label="允许评论">
								<el-switch :active-value="1" :inactive-value="0" v-model="model.isComment"></el-switch>
							</el-form-item>
							<el-form-item label="选择类别">
								<dt-dropdown-check v-model="form.categoryCheckedNodes"
									:data="form.categoryList"
									:checked="form.categoryCheckedKeys">
								</dt-dropdown-check>
							</el-form-item>
							<el-form-item v-if="form.groupList.length>0" prop="groupIds" label="阅读权限">
								<el-checkbox-group v-model="model.groupIds">
									<el-checkbox v-for="(item,i) in form.groupList" :key="item.id" :label="item.id">{{item.title}}</el-checkbox>
								</el-checkbox-group>
							</el-form-item>
							<el-form-item label="显示状态">
								<el-radio-group v-model="model.status">
									<el-radio-button label="0">正常</el-radio-button>
									<el-radio-button label="1">待审核</el-radio-button>
									<el-radio-button label="2">已删除</el-radio-button>
								</el-radio-group>
							</el-form-item>
							<el-form-item v-if="form.labelList.length>0" label="标签属性">
								<el-checkbox-group v-model="form.labelCheckedIds">
									<el-checkbox-button v-for="item in form.labelList" :label="item.id" :key="item.id">{{item.title}}</el-checkbox-button>
								</el-checkbox-group>
							</el-form-item>
							<el-form-item prop="title" label="文章标题">
							    <el-input v-model="model.title" placeholder="必填，250字符内" show-word-limit maxlength="512"></el-input>
							</el-form-item>
							<el-form-item prop="imgUrl" label="封面图片">
								<dt-upload-text v-model="model.imgUrl"
									placeholder="请上传封面图片"
									width="20%"
									height="10%"
									fit="cover"
									:size="form.config.imgSize"
									exts="jpg,jpeg,png,gif"
									action="/upload">
								</dt-upload-text>
							</el-form-item>
							<el-form-item prop="sortId" label="排序数字" :rules="rules.number">
							    <el-input v-model="model.sortId" placeholder="数字越小越排前"></el-input>
							</el-form-item>
							<el-form-item prop="click" label="浏览次数" :rules="rules.number">
							    <el-input v-model="model.click" placeholder=""></el-input>
							</el-form-item>
							<el-form-item prop="source" label="文章来源">
							    <el-input v-model="model.source" placeholder="文章的来源地址"></el-input>
							</el-form-item>
							<el-form-item prop="author" label="文章作者">
							    <el-input v-model="model.author" placeholder="文章作者"></el-input>
							</el-form-item>
							<el-form-item v-if="form.channelModel.isAttach==1" label="附件上传">
								<dt-upload-attach v-model="form.attachList" 
									:size="form.config.attachSize" 
									:exts="form.config.fileExtension">
								</dt-upload-attach>
							</el-form-item>
							<el-form-item v-if="form.channelModel.isAlbum==1" label="相册上传">
								<dt-upload-album v-model="form.albumList" :size="2048"></dt-upload-album>
							</el-form-item>
							<el-form-item label="发布时间">
								<el-date-picker v-model="model.addTime"
									type="datetime"
									value-format="yyyy-MM-dd HH:mm:ss"
									placeholder="发布时间">
								</el-date-picker>
							</el-form-item>
							<el-form-item label="最后更新" v-if="model.id>0&&model.updateTime">
								{{model.updateBy}} {{model.updateTime}}
							</el-form-item>
						</div>
					</el-tab-pane>
					<template v-if="model.articleFields.length>0">
						<el-tab-pane label="扩展选项" name="fields">
							<div class="tab-content">
								<template v-for="(field,index) in model.articleFields">
									<!--单行文本框-->
									<el-form-item v-if="field.controlType=='input'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-input v-if="field.isPassword==0" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
										<el-input v-else v-model="field.fieldValue" :placeholder="field.validTipMsg" show-password></el-input>
									</el-form-item>
									<!--多行文本框-->
									<el-form-item v-else-if="field.controlType=='textarea'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-input type="textarea" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
									</el-form-item>
									<!--编辑器-->
									<el-form-item v-else-if="field.controlType=='editor'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<dt-editor :mini="field.editorType==1" v-model="field.fieldValue" :placeholder="field.validTipMsg"></dt-editor>
									</el-form-item>
									<!--图片上传-->
									<el-form-item v-else-if="field.controlType=='images'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<dt-upload-text v-model="field.fieldValue"
											:placeholder="field.validTipMsg"
											exts="jpg,jpeg,png,gif"
											:size="form.config.imgSize"
											action="/upload">
										</dt-upload-text>
									</el-form-item>
									<!--视频上传-->
									<el-form-item v-else-if="field.controlType=='video'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<dt-upload-text v-model="field.fieldValue"
											:placeholder="field.validTipMsg"
											:exts="form.config.videoExtension"
											:size="form.config.videoSize"
											action="/upload"></dt-upload-text>
									</el-form-item>
									<!--日期时间-->
									<el-form-item v-else-if="field.controlType=='datetime'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-date-picker v-model="field.fieldValue" value-format="yyyy-MM-dd hh:mm:ss" :placeholder="field.validTipMsg" type="datetime">
										</el-date-picker>
									</el-form-item>
									<!--多项单选-->
									<el-form-item v-else-if="field.controlType=='radio'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-radio-group v-model="field.fieldValue">
											<el-radio v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-radio>
										</el-radio-group>
									</el-form-item>
									<!--多项多选-->
									<el-form-item v-else-if="field.controlType=='checkbox'" :prop="'articleFields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-checkbox-group v-model="field.fieldValue">
											<el-checkbox v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-checkbox>
										</el-checkbox-group>
									</el-form-item>
								</template>
							</div>
						</el-tab-pane>
					</template>
					<el-tab-pane label="详细描述" name="details">
						<div class="tab-content">
							<el-form-item prop="callIndex" label="调用别名">
								<el-input v-model="model.callIndex" maxlength="128" placeholder="非必填，单页可做为别名"></el-input>
							</el-form-item>
							<el-form-item prop="linkUrl" label="外部链接">
								<el-input type="text" v-model="model.linkUrl"></el-input>
							</el-form-item>
							<el-form-item prop="zhaiyao" label="内容摘要">
								<el-input type="textarea" :row="3" v-model="model.zhaiyao" show-word-limit maxlength="255"></el-input>
							</el-form-item>
							<el-form-item prop="content" label="内容介绍">
								<dt-editor v-model="model.content" placeholder="请输入内容介绍"></dt-editor>
							</el-form-item>
						</div>
					</el-tab-pane>
					<el-tab-pane label="SEO选项" name="seo">
						<div class="tab-content">
							<el-form-item prop="seoTitle" label="SEO标题">
								<el-input type="text" v-model="model.seoTitle"></el-input>
							</el-form-item>
							<el-form-item prop="seoKeyword" label="SEO关健字">
								<el-input type="text" v-model="model.seoKeyword"></el-input>
							</el-form-item>
							<el-form-item prop="seoDescription" label="SEO描述">
								<el-input type="textarea" :row="3" v-model="model.seoDescription" show-word-limit maxlength="512"></el-input>
							</el-form-item>
						</div>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</div>
		
		<div class="footer-box">
			<div class="footer-btn">
				<el-button type="primary" :loading="loading" @click="submitForm">确认保存</el-button>
				<el-button plain @click="$common.back()">返回上一页</el-button>
			</div>
		</div>
	</dt-main-body>
</template>

<script>
	import DtDropdownCheck from '../../components/DtDropdownCheck.vue'
	import DtUpload from '../../components/DtUpload.vue'
	import DtUploadText from '../../components/DtUploadText.vue'
	import DtUploadAlbum from '../../components/DtUploadAlbum.vue'
	import DtUploadAttach from '../../components/DtUploadAttach.vue'
	import DtEditor from '../../components/DtEditor.vue'
	export default {
		components: {
			DtDropdownCheck,
			DtUpload,
			DtUploadText,
			DtUploadAlbum,
			DtUploadAttach,
			DtEditor
		},
		props: {
			channelId: 0,
			id: 0
		},
		data() {
			return {
				activeName: 'info', //当前选项卡
				labelPosition: 'right', //表单对齐方式
				loading: false,
				copyId: 0,
				loadEdit: null,
				form: {
					categoryList: [], //类别列表
					categoryCheckedKeys: [], //初始化选中健，修改赋值
					categoryCheckedNodes: [],//当前选中类别节点,保存取值
					albumList: [],//相册列表,保存取值
					attachList: [],//附件列表
					labelList: [],//标签列表
					labelCheckedIds: [],//标签选中值,保存取值
					groupList: [],//会员组列表
					channelModel: {},//频道信息
					config: {},//系统信息
				},
				model: {
					id: 0,
					channelId: this.channelId,
					callIndex: null,
					title: null,
					source: '本站',
					author: '管理员',
					linkUrl: null,
					imgUrl: null,
					seoTitle: null,
					seoKeyword: null,
					seoDescription: null,
					zhaiyao: null,
					content: null,
					sortId: 99,
					click: 100,
					status: 0,
					isComment: 1,
					addBy: null,
					addTime: null,
					groupIds: [],
					categoryRelations: [],
					labelRelations: [],
					articleFields: [],
					articleAlbums: [],
					articleAttachs: [],
				},
				rules: {
					callIndex: [
						{ max: 128, message: '别名不可超出128字符', trigger: 'blur' }
					],
					title: [
						{ required: true, message: '标题不可为空', trigger: 'blur' },
						{ max: 512, message: '标题不可超出512字符', trigger: 'blur' }
					],
					source: [
						{ max: 128, message: '来源不可超出128字符', trigger: 'blur' }
					],
					author: [
						{ max: 128, message: '作者不可超出128字符', trigger: 'blur' }
					],
					linkUrl: [
						{ max: 512, message: '外部链接不可超出512字符', trigger: 'blur' }
					],
					imgUrl: [
						{ max: 512, message: '图片地址不可超出512字符', trigger: 'blur' }
					],
					seoTitle: [
						{ max: 512, message: 'SEO标题不可超出512字符', trigger: 'blur' }
					],
					seoKeyword: [
						{ max: 512, message: 'SEO关健字不可超出512字符', trigger: 'blur' }
					],
					seoDescription: [
						{ max: 512, message: 'SEO描述不可超出512字符', trigger: 'blur' }
					],
					zhaiyao: [
						{ max: 255, message: '内容摘要不可超出255字符', trigger: 'blur' }
					],
					content: [
						{ required: true, message: '内容不可为空', trigger: 'blur' },
					],
					categoryRelations: [
						{ type: 'array', required: true, message: '请选择栏目类别', trigger: 'blur' },
					],
					number: [
						{ pattern: /^\d+$/, message: '请输入正确的数字', trigger: 'blur' },
					],
				},
				//字段规则
				fieldRules: {},
			}
		},
		methods: {
			//初始化数据
			async initData() {
				let _this = this;//当前页面
				let id = _this.id;
				_this.copyId = _this.$route.query.copyId;//获取需要复制的ID
				//如果是复制
				if (_this.copyId) {
					id = parseInt(_this.copyId);
				}
				const loading = _this.$loading();
				//获取系统信息
				await _this.$api.request({
					url: `/client/setting/uploadconfig`,
					success(res) {
						_this.form.config = res.data;
				    }
				});
				//获取可用标签
				await _this.$api.request({
					url: `/admin/article/label/view/${_this.model.channelId}/100?status=0`,
					success(res) {
						_this.form.labelList = res.data;
					}
				});
				//获取频道信息
				await _this.$api.request({
					url: `/admin/channel/${_this.channelId}`,
					success(res) {
						_this.form.channelModel = res.data;
					}
				});
				//获取会员组列表
				await _this.$api.request({
					url: '/admin/member/group?status=0',
					success(res) {
						_this.form.groupList = res.data;
					}
				});
				//获取分类列表
				await _this.$api.request({
				    url: `/admin/article/category/${_this.channelId}`,
				    success(res) {
						_this.form.categoryList = res.data;
				    }
				});
				//获取文章信息
				if (id > 0) {
					await _this.$api.request({
						url: `/admin/article/${_this.channelId}/${id}`,
						success(res) {
							//赋值给model
							Object.keys(_this.model).forEach(key => { _this.model[key] = res.data[key] });
							//如果是复制，将ID设置为0
							if (_this.copyId) {
								_this.model.id = 0;
							}
							//给标签选中赋值
							if (_this.model.labelRelations) {
								_this.model.labelRelations.map(item => {
									_this.form.labelCheckedIds.push(item.labelId);
								});
							}
							//给类别设置选中赋值
							if (_this.model.categoryRelations) {
								let categoryIds = [];
								_this.model.categoryRelations.map(item => {
									categoryIds.push(item.categoryId);
								});
								_this.form.categoryCheckedKeys = categoryIds;
							}
							//赋值给会员组选中
							if (_this.model.groupIds) {
								let groupIds = _this.model.groupIds.replace(/^,+/, "").replace(/,+$/, "").split(",");
								_this.model.groupIds = groupIds.map(Number);
							} else {
								_this.model.groupIds = [];
							}
						}
					});
				}
				//初始化扩展字段
				_this.initFields();
				//相册赋值
				if (_this.model.articleAlbums) {
					_this.model.articleAlbums.map((item) => {
						item.url = item.thumbPath;
						_this.form.albumList.push(item);
					})
				}
				//附件赋值
				if (_this.model.articleAttachs) {
					_this.model.articleAttachs.map((item) => {
						item.fileName = item.fileName;
						item.articleId = item.articleId;
						item.filePath = item.filePath;
						item.fileSize = item.fileSize;
						item.fileExt = item.fileExt;
						item.downCount = item.downCount;
						_this.form.attachList.push(item);
					})
				}
				loading.close();
			},
			//初始化扩展字段
			initFields() {
				let _this = this;
				//重置验证规则
				_this.fieldRules = {};
				_this.form.channelModel.fields.forEach((val, i) => {
					//编辑的时候触发
					if (_this.model.id>0 || _this.copyId>0) {
						//获得扩展字段值
						let obj = getFieldsValue(val.name);
						//构建ArticleFields属性
						val.fieldName = val.name;
						val.fieldId = val.id;
						val.id = obj.id;
						val.articleId = _this.model.id;
						//如果值存在，将值替换默认值
						if (obj.value) {
							//如果是数组
							if (Array.isArray(val.fieldValue)) {
								val.fieldValue = obj.value.split(',');
							} else {
								val.fieldValue = obj.value;
							}
						} else {
							if (Array.isArray(val.fieldValue)) {
								val.fieldValue = [];
							} else {
								val.fieldValue = '';
							}
						}
					} else {
						//构建ArticleFields属性
						val.fieldName = val.name;
						val.fieldId = val.id;
						val.articleId = 0;
					}
					//生成验证规则
					getRules(val);
					//console.log(_this.fieldRules)
				});
				_this.model.articleFields = _this.form.channelModel.fields;
				//获得扩展字段值
				function getFieldsValue(name) {
					let obj = { value: '', id: 0 };
					if (_this.model.articleFields.length > 0) {
						_this.model.articleFields.forEach((val, index) => {
							if (val.fieldName == name) {
								obj = { value: val.fieldValue, id: val.id };
							}
						});
					}
					return obj;
				};
				//生成验证规则
				function getRules(obj) {
					let item = [];
					//blur验证的控件
					if (obj.controlType == 'input' ||
						obj.controlType == 'textarea' ||
						obj.controlType == 'editor' ||
						obj.controlType == 'images' ||
						obj.controlType == 'video' ||
						obj.controlType == 'datetime'
					) {
						//必填项
						if (obj.isRequired == 1) {
							let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'blur' };
							item.push(eleRule);
						}
						//检查正则是否为null
						if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
							//不为空，将字符串转成正则表达式
							let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'blur' }
							item.push(eleRule);
						}

					} else if (obj.controlType == 'radio' ||
						obj.controlType == 'checkbox') {
						//change验证的控件
						//必填项
						if (obj.isRequired == 1) {
							let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'change' };
							item.push(eleRule);
						}
						//检查正则是否为null
						if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
							//不为空，将字符串转成正则表达式
							let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'change' }
							item.push(eleRule);
						}
					}
					let name = obj.name;
					_this.fieldRules[name] = item;
				};
			},
			//表单提交
			submitForm() {
				let _this = this; //当前页面
				//多个表单验证
				const f1 = new Promise((resolve, reject) => {
					_this.$refs['editForm'].validate((valid) => {
						if (valid) resolve();
					});
				});
				Promise.all([f1]).then(() => {
					//检查及组合参数
					if (_this.form.categoryCheckedNodes.length === 0) {
						_this.$message({ type: 'warning', message: '错误提示：请选择文章类别' });
						return false;
					}
					//复制而不是赋值
					let model = JSON.parse(JSON.stringify(_this.model));
					
					//处理扩展字段
					model.articleFields.forEach((val, index) => {
						if (Array.isArray(val.fieldValue)) {
							val.fieldValue = val.fieldValue.join(',');
						}
						//如果是复制
						if (_this.copyId) {
							val.id = 0;
						}
					});
					//分类取值
					let categoryRelations = [];
					_this.form.categoryCheckedNodes.map(function (item) {
					    let modelt = {
							id: 0,
							articleId: model.id,
							categoryId: item.id
					    }
					    //遍历Model已有值，防止ID丢失
					    model.categoryRelations.map(function (v) {
							if (modelt.categoryId === v.categoryId) {
								modelt.id = !_this.copyId ? v.id : 0;//复制id为0
							}
					    });
					    categoryRelations.push(modelt);
					});
					model.categoryRelations = categoryRelations;
					//相册取值
					let albumList = [];
					_this.form.albumList.map(function (item) {
						albumList.push({
							id: !_this.copyId ? item.id : 0,//复制id为0
							articleId: _this.model.id,
							thumbPath: item.thumbPath,
							originalPath: item.originalPath,
							remark: item.remark
						});
					});
					model.articleAlbums = albumList;
					//附件取值
					let attachList = [];
					_this.form.attachList.map(function (item) {
						attachList.push({
							id: !_this.copyId ? item.id : 0,//复制id为0
							fileName: item.fileName,
							articleId: _this.model.id,
							filePath: item.filePath,
							fileSize: item.fileSize,
							fileExt: item.fileExt,
							downCount: item.downCount,
						});
					});
					model.articleAttachs = attachList;
					//标签取值
					let labelRelations = [];
					_this.form.labelCheckedIds.map(function (id) {
						let modelt = {
							id: 0,
							articleId: _this.model.id,
							labelId: id
						}
						//遍历Model已有值，防止ID丢失
						_this.model.labelRelations.map(function (v) {
							if (modelt.labelId === v.labelId) {
								modelt.id = !_this.copyId ? v.id : 0;//复制id为0
							}
						});
						labelRelations.push(modelt);
					});
					model.labelRelations = labelRelations;
					//格式化会员组ID
					if (model.groupIds && model.groupIds.length > 0) {
						model.groupIds = ',' + model.groupIds.toString() + ',';
					} else {
						model.groupIds = null;
					}
					
					//console.log(model)
					//提交表单,Id大于0则修改，否则添加
					if (model.id > 0) {
						_this.$api.request({
							method: 'put',
							url: `/admin/article/${_this.channelId}/${model.id}`,
							data: model,
							successMsg: '修改文章成功',
							beforeSend() {
								_this.loading = true;
							},
							success(res) {
								//跳转到列表页
								_this.$common.linkUrl(`/article/list/${_this.channelId}`);
							},
							complete() {
								_this.loading = false
							}
						});
					} else {
						_this.$api.request({
							method: 'post',
							url: `/admin/article/${_this.channelId}`,
							data: model,
							successMsg: '新增文章成功',
							beforeSend() {
								_this.loading = true;
							},
							success(res) {
								//重置表单
								_this.$refs['editForm'].resetFields();
							},
							complete() {
								_this.loading = false
							}
						});
					}
				})
			},
		},
		created() {
			this.initData();
		}
	}
</script>

<style lang="scss">
</style>